package com.woniuxy.service.impl;

import com.woniuxy.entity.SysDoctor;
import com.woniuxy.entity.SysTeam;
import com.woniuxy.mapper.SysDoctorTeamMapper;
import com.woniuxy.mapper.SysTeamMapper;
import com.woniuxy.service.SysDoctorTeamService;
import com.woniuxy.util.ResponseEnum;
import com.woniuxy.util.ResponseUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统医生团队服务实现类
 * 实现系统医生团队相关的业务逻辑
 */
@Service
public class SysDoctorTeamServiceImpl implements SysDoctorTeamService {
    @Resource
    private SysDoctorTeamMapper sysDoctorTeamMapper;
    @Resource
    private SysTeamMapper sysTeamMapper;
    /**
     * 根据角色和医生ID查询系统团队
     * @param role 角色
     * @param doctorId 医生ID
     * @return 返回指定角色和医生的团队信息
     */
    @Override
    public ResponseUtil findSysTeam(Integer role, Integer doctorId) {
        List<SysTeam> sysTeam = sysDoctorTeamMapper.findSysTeam(role, doctorId);
        return sysTeam!=null?ResponseUtil.get(ResponseEnum.OK,sysTeam)
                :ResponseUtil.get(ResponseEnum.FAIL);
    }
    /**
     * 更新系统医生团队关联关系
     * @param doctorId 医生ID
     * @param teamId 团队ID
     * @return 返回更新操作的响应结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseUtil updateSysDoctorTeam(Integer doctorId, Integer teamId) {
        Integer integer = sysDoctorTeamMapper.updateSysDoctorTeam(doctorId, teamId);
        if (integer<=0){
            throw new RuntimeException("退出团队失败");
        }
        Integer updateTeamCount = sysTeamMapper.updateTeamCount(teamId);
        if (updateTeamCount<=0){
            throw new RuntimeException("团队人数减1失败");
        }
        return ResponseUtil.get(ResponseEnum.OK);
    }

    @Override
    public ResponseUtil findMembersByTeamId(Integer teamId) {
        List<SysDoctor> members = sysDoctorTeamMapper.findMembersByTeamId(teamId);
        return members != null ? ResponseUtil.get(ResponseEnum.OK, members)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    /**
     * 添加团队成员
     * @param doctorId 医生ID
     * @param teamId 团队ID
     * @return 返回添加结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseUtil addDoctorTeamMember(Integer doctorId, Integer teamId) {
        Integer addDoctorTeam = sysDoctorTeamMapper.addDoctorTeamMember(doctorId, teamId);
        if (addDoctorTeam<=0){
            throw new RuntimeException("添加团队成员失败");
        }
        Integer updateTeamCountAdd = sysTeamMapper.updateTeamCountAdd(teamId);
        if (updateTeamCountAdd<=0){
            throw new RuntimeException("团队人数加1失败");
        }
        return ResponseUtil.get(ResponseEnum.OK);
    }
}
